//
//  detailViewController.swift
//  ZTC_Final
//
//  Created by xy Man on 2022/5/25.
//

import UIKit

class detailViewController: UIViewController {

    var name:String = ""
    var price:String = ""
    var ddescription:String = ""
    var pic_path = ""
    var ISBN = ""
    var author = ""
    
    @IBOutlet weak var img: UIImageView!
    
    @IBOutlet weak var bookName: UILabel!
    
    @IBOutlet weak var bookAuthor: UILabel!
    
    @IBOutlet weak var bookISBN: UILabel!
    
    @IBOutlet weak var bookPrice: UILabel!
    
    @IBOutlet weak var bookDscrip: UILabel!
    
    @IBOutlet weak var numberInUser: UILabel!
    
    
    var username:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        print(name)
//        print(price)
//        print(ddescription)
//        print(pic_path)
//        print(ISBN)
//        print(author)
//        print("详细页\(username!)")
        // Do any additional setup after loading the view.
        bookName.text = name
        bookAuthor.text = author
        bookPrice.text = price + "元/本"
        bookISBN.text = ISBN
        bookDscrip.text = "\(ddescription)\n"
        // 从网络上获取图片
        let pic_path:String = pic_path
        let nsurl = NSURL(string: pic_path)
        let nsd = NSData(contentsOf: nsurl! as URL)
        let myImage = UIImage(data: nsd! as Data)
        img.image = myImage
        // 该用户选择的数量
        numberInUser.text = "已选\(getSigleNum())本"
    }
    
    func getSigleNum()->Int{
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return -1}
        let tmpsql = "SELECT number FROM shopping WHERE username='\(username!)' AND bookname = '\(name)';"
        let queryres = sqlite.execQuerySQL(sql: tmpsql)
        sqlite.closeDB()
        if queryres!.count == 0{
            return 0
        }else{
            return queryres![0]["number"] as! Int
        }
    }
    
    @IBAction func addPressed(_ sender: Any) {
        let tmpsql = "SELECT number FROM shopping WHERE username='\(username!)' AND bookname='\(name)';"
        let nav2  = self.tabBarController!.viewControllers![1] as? UINavigationController
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return}
        let queryres = sqlite.execQuerySQL(sql: tmpsql)
        var current_count:Int

        if queryres!.count == 0{
            current_count = 0
        }else{
            current_count = queryres![0]["number"] as! Int
        }
        
//        let queryres1 = sqlite.execQuerySQL(sql: tmpsql)![0]["COUNT(*)"]
        sqlite.closeDB()
        var new_count:Int = 0
        if current_count > 0{
            new_count = current_count + 1
            if !sqlite.openDB(){return}
            let addSql = "UPDATE shopping SET number='\(new_count)' WHERE username='\(username!)' AND bookname='\(name)';"
            if !sqlite.execNoneQuerySQL(sql: addSql){return}
            sqlite.closeDB()
            let current_badge:Int = Int((nav2?.tabBarItem.badgeValue! ?? nil)! as String)!
            nav2?.tabBarItem.badgeValue = "\(current_badge+1)"
        }else{
            let addSql = "REPLACE INTO shopping VALUES('\(username!)','\(name)',1);"
            if !sqlite.openDB(){return}
            if !sqlite.execNoneQuerySQL(sql: addSql){return}
            sqlite.closeDB()
            new_count += 1
            let current_badge:Int = Int((nav2?.tabBarItem.badgeValue! ?? nil)! as String)!
            nav2?.tabBarItem.badgeValue = "\(current_badge+1)"
//            let nav2 = self.viewControllers![1] as? UINavigationController
//            nav2?.tabBarItem.badgeValue = "\(totalNUm)"
        }
        numberInUser.text = "已选\(new_count)本"
        // 重新加载购物车数据
        let shoppingBar = nav2?.viewControllers.first as! ShoppingTableViewController
        shoppingBar.tableView.reloadData()
        
    }
    
    
    
    @IBAction func subPressed(_ sender: Any) {
        let tmpsql = "SELECT number FROM shopping WHERE username='\(username!)' AND bookname='\(name)';"
        let nav2  = self.tabBarController!.viewControllers![1] as? UINavigationController
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return}
        let queryres = sqlite.execQuerySQL(sql: tmpsql)
        var current_count:Int
        if queryres!.count == 0{
            current_count = 0
        }else{
            current_count = queryres![0]["number"] as! Int
        }

        
//        let queryres1 = sqlite.execQuerySQL(sql: tmpsql)![0]["COUNT(*)"]
        sqlite.closeDB()
        var new_count:Int = 0
        if current_count > 0{
            new_count = current_count - 1
            if !sqlite.openDB(){return}
            let addSql = "UPDATE shopping SET number='\(new_count)' WHERE username='\(username!)' AND bookname='\(name)';"
            if !sqlite.execNoneQuerySQL(sql: addSql){return}
            sqlite.closeDB()
            let current_badge:Int = Int((nav2?.tabBarItem.badgeValue! ?? nil)! as String)!
            nav2?.tabBarItem.badgeValue = "\(current_badge-1)"
        }else{
//            let addSql = "REPLACE INTO shopping VALUES('\(username!)','\(name)',1);"
//            if !sqlite.openDB(){return}
//            if !sqlite.execNoneQuerySQL(sql: addSql){return}
//            sqlite.closeDB()
        }
        numberInUser.text = "已选\(new_count)本"
        // 重新加载购物车数据
        let shoppingBar = nav2?.viewControllers.first as! ShoppingTableViewController
        shoppingBar.tableView.reloadData()

    }
    
    override func viewWillAppear(_ animated: Bool) {
        // 重新加载购买数
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return}
        let sql = "SELECT number FROM shopping WHERE username='\(username!)' AND bookname='\(name)';"
        let queryres = sqlite.execQuerySQL(sql: sql)
        sqlite.closeDB()
        if queryres!.count > 0{
        numberInUser.text = "\(queryres![0]["number"] as! Int)"
        }else{
            numberInUser.text = "已选0本"
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    

}
